const { BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const store = require(path.join(__dirname, "../../store/store"));
module.exports = class CreateAddServeWindow {
  constructor(parent) {
    this.parent = parent;
    this.createWindow();
  }
  createWindow = () => {
    this.win = new BrowserWindow({
      width: 500,
      height: 600,
      parent: this.parent,
      show: false,
      modal: true,
      frame: false,
      resizable: false,
      maximizable: false,
      webPreferences: {
        preload: path.join(__dirname, "../preload.js"),
      },
    });
    this.win.loadFile(path.join(__dirname, "../../page/addServe/index.html"));
  };
  show = () => {
    this.win.show();
  };
  close = () => {
    this.win.close();
  };
};

ipcMain.on("closeAddServe", async (event) => {
  BrowserWindow.fromWebContents(event.sender).close();
});

ipcMain.on("savaServer", (event, message) => {
  if (!store.has("serverList")) {
    store.set("serverList", []);
  }

  let serverList = store.get("serverList");
  let foundDuplicate = false;
  // 检查是否存在重复的 IP 地址
  serverList.forEach((item) => {
    if (item.ip === message.ip) {
      foundDuplicate = true;
      // 如果重复，则更新名称和密码
      item.name = message.name;
      item.password = message.password;
    }
  });
  // 如果没有重复，则将新服务器添加到列表中
  if (!foundDuplicate) {
    serverList.push(message);
  }

  store.set("serverList", serverList);
});
